package com.yc.ycrpc;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 管理rpc暴露的服务
 * @author yc112
 */
@Slf4j
public class ServiceManager {

    private Map<ServiceDescriptor, ServiceInstance> serviceInstanceMap;

    public ServiceManager () {
        serviceInstanceMap = new ConcurrentHashMap<>();
    }

    /**
     * @param interfaceClass 接口Class
     * @param bean 接口具体对象
     */
    public <T> void register(Class<T> interfaceClass, T bean) {
        Method[] publicMethod = ReflectionUtils.getPublicMethod(interfaceClass);
        for (Method m : publicMethod) {
            ServiceInstance sis = new ServiceInstance(bean, m);
            ServiceDescriptor serviceDescriptor = ServiceDescriptor.from(interfaceClass, m);
            serviceInstanceMap.put(serviceDescriptor, sis);
            log.info("register service: {} {}", serviceDescriptor.getClazz(), serviceDescriptor.getMethod());
        }
    }


    public ServiceInstance lookup(Request request) {
        ServiceDescriptor serivice = request.getSerivice();
        return serviceInstanceMap.get(serivice);
    }
}
